<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--工厂模型数据-->
      <el-col :lg="6" style="padding-right: 2%; border-right: 1px #dcdfe6 solid">
        <div class="head-container1">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['base:shop:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['base:shop:edit']"
              >修改</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-dropdown>
                <el-button
                  type="primary"
                  icon="el-icon-d-arrow-right"
                  size="mini"
                >更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <el-col :span="1.5">
                        <el-button
                          type="info"
                          plain
                          icon="el-icon-upload2"
                          size="mini"
                          @click="handleImport"
                          v-hasPermi="['base:shop:import']"
                        >导入</el-button>
                      </el-col>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-col :span="1.5">
                        <el-button
                          type="warning"
                          plain
                          icon="el-icon-download"
                          size="mini"
                          style="margin-top: 10px"
                          @click="handleExport"
                          v-hasPermi="['base:shop:export']"
                        >导出</el-button>
                      </el-col>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-col> -->
          </el-row>
        </div>
        <div class="head-container">
          <el-input
            v-model="SelectshopName"
            placeholder="请输入名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="shopOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :highlight-current="true"
            :current-node-key="currentLivingId"
            ref="tree"
            node-key="id"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--工厂模型数据-->
      <el-col :lg="17" style="margin-left: 1%">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item :label="OptionCode" prop="shopName" style="margin-right: 24px">
            <el-input
              v-model="queryParams.shopName"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="OptionName" prop="shopCode">
            <el-input
              v-model="queryParams.shopCode"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 卡片风格 -->
        <el-row style="display: flex; justify-content: flex-start; flex-wrap: wrap">
          <el-col
            v-for="item in shopList"
            :key="item.id"
            :sm="6"
            style="margin-bottom: 10px"
            :inline="true"
          >
            <el-card style="margin-right: 20px">
              <div slot="header" class="clearfix">
                <i class="el-icon-user" /><span style="margin-left: 5px">{{item.createBy}}</span>
                <div
                  style="display: inline-block; float: right; cursor: pointer"
                  v-hasPermi="['base:shop:edit']"
                  @click="handleUpdate2(item)"
                >
                  <el-tooltip effect="dark" content="编辑" placement="top">
                    <i class="el-icon-edit-outline" style="margin-left: 15px" />
                  </el-tooltip>
                </div>
              </div>
              <div>
                <ul class="role-info">
                  <li>
                    <div class="role-left">{{ OptionCode }}：{{ item.shopCode }}</div>
                  </li>
                  <li>
                    <div class="role-left">{{ OptionName }}：{{ item.shopName }}</div>
                  </li>
                </ul>
              </div>
              <div
                style="display: inline-block; float: right; cursor: pointer"
                v-hasPermi="['base:shop:remove']"
                @click="handleDelete(item)"
              >
                <el-tooltip effect="dark" content="删除" placement="bottom">
                  <i class="el-icon-delete" style="margin-left: 15px" />
                </el-tooltip>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="上级" prop="parentId" v-if="false">
          <el-input v-model="form.parentId" />
        </el-form-item>
        <el-form-item label="类型" prop="shopType" v-if="false">
          <el-input v-model="form.shopType" />
        </el-form-item>
        <el-form-item label="上级名称">{{ this.ParentshopName }}</el-form-item>
        <el-form-item :label="OptionCode" prop="shopCode">
          <el-input
            v-model="form.shopCode"
            :placeholder="'请输入' + OptionCode"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item :label="OptionName" prop="shopName">
          <el-input
            v-model="form.shopName"
            :placeholder="'请输入' + OptionName"
            style="width: 240px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改参数配置对话框 -->
    <el-dialog :title="title1" :visible.sync="open1" width="500px" @close="cancel1">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="上级" prop="parentId" v-if="false">
          <el-input v-model="form.parentId" />
        </el-form-item>
        <el-form-item label="类型" prop="shopType" v-if="false">
          <el-input v-model="form.shopType" />
        </el-form-item>
        <el-form-item label="上级名称">{{ this.ParentshopName }}</el-form-item>
        <el-form-item :label="TreeUpdateCode" prop="shopCode">
          <el-input
            v-model="form.shopCode"
            :placeholder="'请输入' + OptionCode"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item :label="TreeUpdateName" prop="shopName">
          <el-input
            v-model="form.shopName"
            :placeholder="'请输入' + OptionName"
            style="width: 240px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改参数配置对话框 -->
    <el-dialog :title="title2" :visible.sync="open2" width="500px" @close="cancel2">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="上级" prop="parentId" v-if="false">
          <el-input v-model="form.parentId" />
        </el-form-item>
        <el-form-item label="类型" prop="shopType" v-if="false">
          <el-input v-model="form.shopType" />
        </el-form-item>
        <el-form-item label="上级名称">{{ this.ParentshopName }}</el-form-item>
        <el-form-item :label="UpdateCode" prop="shopCode">
          <el-input
            v-model="form.shopCode"
            :placeholder="'请输入' + OptionCode"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item :label="UpdateName" prop="shopName">
          <el-input
            v-model="form.shopName"
            :placeholder="'请输入' + OptionName"
            style="width: 240px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 工厂模型导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        name="file"
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的工厂数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  treeselect,
  getTreeList,
  addShop,
  delShop,
  updateShop,
  getShop,
} from "@/api/base/shopConfig";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "user",
  components: { Treeselect },
  data() {
    return {
      currentLivingId: "",
      SelectshopName: undefined,
      OptionName: "",
      OptionCode: "",
      UpdateName: "",
      UpdateCode: "",
      TreeUpdateName: "",
      TreeUpdateCode: "",
      ParentshopName: "",
      // 字典弹出层
      StationVisible: false,
      // 遮罩层
      loading: true,
      // 选中userId数组
      ids: [],
      // 非单个禁用
      single: false,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      shopList: [],
      // 弹出层标题
      title: "",
      title1: "",
      title2: "",
      // 工厂建模树选项
      shopOptions: undefined,
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "base/shop/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopName: undefined,
        shopCode: undefined,
        parentId: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `登录IP`, checked: false },
        { key: 1, label: `最后登录时间`, checked: false },
        { key: 2, label: `创建人`, checked: false },
        { key: 3, label: `备注`, checked: false },
      ],
      // 表单校验
      rules: {
        shopCode: [
          {
            required: true,
            message: `不能为空`,
            trigger: "blur",
          },
        ],
        shopName: [
          {
            required: true,
            message: `不能为空`,
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    SelectshopName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getTreeselect();
  },
  methods: {
    /** 查询工厂列表 */
    getList() {
      this.loading = true;
      getTreeList(this.queryParams).then((response) => {
        this.shopList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询工厂模型下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.shopOptions = response.data;
        if (this.shopOptions.length > 0) {
          this.currentLivingId = this.shopOptions[0].id;
          this.queryParams.parentId = this.currentLivingId;
          this.ParentshopName = "";
          this.form = {
            shopCode: undefined,
            shopName: undefined,
            parentId: this.currentLivingId,
            shopType: parseInt(this.shopOptions[0].type + 1),
          };
          this.judeType(this.shopOptions[0]);
          this.$nextTick(function () {
            this.$refs.tree.setCurrentKey(this.currentLivingId);
          });
          this.getList();
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    judeType(data) {
      //1 2 3 4 5 6
      switch (data.type) {
        case 0:
          this.OptionName = "工厂名称";
          this.OptionCode = "工厂编码";
          this.TreeUpdateName = "集团名称";
          this.TreeUpdateCode = "集团编码";
          this.form.shopType = 1;
          break;
        case 1:
          this.OptionName = "车间名称";
          this.OptionCode = "车间编码";
          this.TreeUpdateName = "工厂名称";
          this.TreeUpdateCode = "工厂编码";
          this.form.shopType = 2;
          break;
        case 2:
          this.OptionName = "产线名称";
          this.OptionCode = "产线编码";
          this.TreeUpdateName = "车间名称";
          this.TreeUpdateCode = "车间编码";
          this.form.shopType = 3;
          break;
        case 3:
          this.OptionName = "工位名称";
          this.OptionCode = "工位编码";
          this.TreeUpdateName = "产线名称";
          this.TreeUpdateCode = "产线编码";
          this.form.shopType = 4;
          break;
        case 4:
          this.OptionName = "设备名称";
          this.OptionCode = "设备编码";
          this.TreeUpdateName = "工位名称";
          this.TreeUpdateCode = "工位编码";
          this.form.shopType = 5;
          break;
        default:
          this.TreeUpdateName = "设备名称";
          this.TreeUpdateCode = "设备编码";
          break;
      }
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.parentId = data.id;
      this.form.parentId = data.id;
      this.judeType(data);
      this.ParentshopName = data.label;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancel1() {
      this.open1 = false;
      this.reset();
    },

    cancel2() {
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form.shopCode = undefined;
      this.form.shopName = undefined;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.shopName = "";
      this.queryParams.shopCode = "";
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.TreeUpdateName == "设备名称") {
        this.msgError("目前层级支持设备级！");
        return;
      }
      this.open = true;
      this.title = "新增" + this.OptionName.slice(0, 2);
    },
    /** 修改按钮操作 */
    handleUpdate() {
      if (this.queryParams.parentId == undefined) {
        this.msgError("请选择一条数据！");
      }
      this.reset();
      getShop(this.queryParams.parentId).then((response) => {
        // this.form = response.data.user;
        this.form = response.data;
        this.open1 = true;
        this.title1 = "修改" + this.UpdateName.slice(0, 2);
      });
    },
    /** 修改按钮操作 */
    handleUpdate2(item) {
      if (this.queryParams.parentId == undefined) {
        this.msgError("请选择一条数据！");
      }
      this.reset();
      this.UpdateCode1 = this.UpdateCode;
      this.UpdateName1 = this.UpdateName;
      switch (item.shopType) {
        case 0:
          this.UpdateName = "集团名称";
          this.UpdateCode = "集团编码";
          break;
        case 1:
          this.UpdateName = "工厂名称";
          this.UpdateCode = "工厂编码";
          break;
        case 2:
          this.UpdateName = "车间名称";
          this.UpdateCode = "车间编码";
          break;
        case 3:
          this.UpdateName = "产线名称";
          this.UpdateCode = "产线编码";
          break;
        case 4:
          this.UpdateName = "工位名称";
          this.UpdateCode = "工位编码";
          break;
        default:
          this.UpdateName = "设备名称";
          this.UpdateCode = "设备编码";
          break;
      }
      getShop(item.shopId).then((response) => {
        // this.form = response.data.user;
        this.form = response.data;
        this.open2 = true;
        this.title2 = "修改" + this.UpdateName.slice(0, 2);
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(JSON.stringify(this.form));
          // return;
          if (this.form.shopId != undefined) {
            updateShop(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open1 = false;
              this.open2 = false;
              this.UpdateCode = this.UpdateCode1;
              this.UpdateName = this.UpdateName1;
              this.getTreeselect();
            });
          } else {
            addShop(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getTreeselect();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除工厂模型为"' + row.shopCode + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delShop(row.shopId);
        })
        .then(() => {
          this.getTreeselect();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有用户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        exportUser(queryParams).then((response) => {
          const { code, data } = response;
          if (code == 200) {
            this.msgSuccess("导出成功");
            this.download(data.path);
          } else {
            this.msgError("导出失败");
          }
        });
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download("system/user/importTemplate", "用户数据导入模板");
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /**
     * 解决编辑时角色选中不了问题
     */
    selectRole(e) {
      console.log(e, JSON.stringify(this.form));
      this.$forceUpdate();
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}
.role-info {
  margin-top: 0;
  padding-top: 0;
  padding-left: 0;
  list-style: none;
  li {
    border-bottom: 1px solid #f0f3f4;
    padding: 11px 0;
    font-size: 12px;
  }
  .role-left {
    color: rgb(148, 137, 137);
    overflow: hidden;
    white-space: nowrap;
    text-align: left;
    text-overflow: ellipsis;
  }

  .line {
    width: 100%;
    height: 1px;
    border-top: 1px solid #ccc;
  }
}

.card-toggle-table {
  padding: 4px 0;
  display: -webkit-flex;
  display: flex;
  float: right;
  align-items: center;
  margin-left: auto;
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
::v-deep .vue-treeselect__multi-value {
  margin-bottom: 0;
}
::v-deep .vue-treeselect__multi-value-item {
  border: 0;
  padding: 0;
}
</style>
<style>
/* 点击树结构项的选中颜色 */
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #b0c4de;
}
</style>
